<template>
	<view class="cart-page" :class="['qn-page-' + theme]">
		<view class="container">
			<!-- 未登录 -->
			<view v-if="!isLogin" class="empty-wrapper">
				<u-empty mode="permission" text="您还未登录，请登录后操作">
					<u-button
						slot="bottom"
						type="primary"
						size="medium"
						@click="goToLogin"
						:custom-style="{ marginTop: '40rpx', backgroundColor: primaryColor, color: '#fff' }"
					>
						去登录
					</u-button>
				</u-empty>
			</view>
			<!-- 购物车为空 -->
			<Aempty
				text="购物车竟然是空的"
				src="https://devapi.dinghuomiao.com/uploads/20250701/%E8%B4%AD%E7%89%A9%E8%BD%A6%E7%A9%BA%E7%A9%BA.png"
				v-else-if="invalidData.length === 0 && goodsData.length === 0"
			></Aempty>

			<view v-else>
				<!-- 列表 goodsData -->
				<view class="cart-card" v-for="(item, index) in goodsData" :key="index">
					<view class="shop-header">
						<u-icon
							:name="item.checkedShop ? 'checkmark-circle-fill' : 'checkmark-circle'"
							:color="item.checkedShop ? primaryColor : '#c8c9cc'"
							size="40"
							@click="checkShop(item.checkedShop, item.shopId, 2, item)"
						></u-icon>
						<text class="shop-name u-line-1">{{ item.shopName }}</text>
						<u-icon name="arrow-right" color="#999" size="28"></u-icon>
					</view>
					<u-swipe-action
						v-for="(goods, goodsindex) in item.shopGoodsData"
						:key="goodsindex"
						:show="goods.isShow"
						:index="goodsindex"
						:options="options"
						@open="openItem(index, goodsindex)"
						@click="deleteCartItem([goods.cartId], goods)"
					>
						<view class="goods-item">
							<u-icon
								:name="goods.selection === 5 ? 'checkmark-circle-fill' : 'checkmark-circle'"
								:color="goods.selection === 5 ? primaryColor : '#c8c9cc'"
								size="40"
								class="checkbox"
								@click="checkShop(goods.selection === 5, goods.cartId, 1, goods, item)"
							></u-icon>
							<image class="goods-image" :src="goods.goodsImages" mode="aspectFill" @click="goPage(`/pagesT/product/product?id=${goods.goodsId}`)"></image>
							<view class="goods-info">
								<view class="goods-title" @click="goPage(`/pagesT/product/product?id=${goods.goodsId}`)">{{ goods.goodsName }}</view>
								<view class="goods-sku" @click="goPage(`/pagesT/product/product?id=${goods.goodsId}`)">
									<block v-if="goods.specGroup && goods.specGroup.length">
										<text v-for="(sku, skui) in goods.specGroup" :key="skui" style="padding-right: 4upx;">{{ sku.specValueName }};</text>
									</block>
								</view>
								<view class="goods-bottom">
									<view class="price-box">
										<text class="price-symbol">¥</text>
										<view style="display: inline-block;"><rich-text class="price" :nodes="$_utils.splitPrice(goods.price)"></rich-text></view>
										<text class="unit">/{{ goods.unitName }}</text>
										<view v-if="goods.isActivity === 5" class="activity-tag">活动价</view>
									</view>
									<block v-if="goods.isDistribution === 5">
										<!-- 开启预售不验证最大值 -->
										<u-number-box
											:bg-color="primaryColor"
											color="#fff"
											:value="goods.buyNum"
											:input-height="44"
											:min="goods.setNum"
											@blur="numberChange($event, goods)"
											@plus="clacAdd($event, goods)"
											@minus="clacSusubtract($event, goods)"
										></u-number-box>
									</block>
									<block v-else>
										<!-- 未开启预售最大值为库存数 -->
										<u-number-box
											:bg-color="primaryColor"
											color="#fff"
											:value="goods.buyNum"
											:input-height="44"
											:max="Number(goods.inventoryNum)"
											:min="goods.setNum"
											@blur="numberChange($event, goods)"
											@plus="clacAdd($event, goods)"
											@minus="clacSusubtract($event, goods)"
										></u-number-box>
									</block>
								</view>
							</view>
						</view>
					</u-swipe-action>
				</view>
				<!-- 失效商品 -->
				<view class="cart-card invalid-card" v-if="invalidData.length">
					<view class="invalid-header">
						<text class="invalid-title">失效商品（{{ invalidData.length }}）</text>
						<view class="clear-btn" @click="clearInvalid"><u-icon name="trash" size="32" style="margin-right: 4rpx;"></u-icon>清空</view>
					</view>
					<view class="goods-item" v-for="(goods, goodsindex) in invalidData" :key="goodsindex" style="padding-left: 0;">
						<view class="invalid-tag">失效</view>
						<image class="goods-image" :src="goods.goodsImages" mode="aspectFill"></image>
						<view class="goods-info">
							<view class="goods-title disabled">{{ goods.goodsName }}</view>
							<view class="invalid-reason">{{ goods.invalidMsg }}</view>
						</view>
					</view>
				</view>
			</view>
		</view>
		<!-- 底部菜单栏 -->
		<view class="action-section" v-if="isLogin && goodsData.length" :style="{ bottom: isBang ? '170rpx' : '100rpx' }">
			<view class="action-main">
				<view class="select-all" @click="checkShop(allChecked, '', 3)">
					<u-icon :name="allChecked ? 'checkmark-circle-fill' : 'checkmark-circle'" :color="allChecked ? primaryColor : '#c8c9cc'" size="40"></u-icon>
					<text class="text">全选</text>
				</view>

				<view class="right-area">
					<view class="total-box" v-if="!is_edit">
						<view class="price-line">
							<text class="label">合计：</text>
							<text class="price">¥{{ $_utils.formatNub(goodsDataAll.payMoney) || 0 }}</text>
						</view>
						<view class="sub-line" @click="goPage('/pages/classification/cate', 'switchTab')">
							<block v-if="!goodsDataAll.totalMoney && startDeliveryPrice">
								满{{ startDeliveryPrice }}元起送，先去逛逛
								<u-icon name="arrow-right" size="20" color="#999"></u-icon>
							</block>
							<block v-else-if="startDeliveryPrice && goodsDataAll.totalMoney < startDeliveryPrice">
								还差{{ $NP.minus(startDeliveryPrice, goodsDataAll.totalMoney) }}元起送
								<u-icon name="arrow-right" size="20" color="#999"></u-icon>
							</block>
							<block v-else-if="freeExpressPrice > 0">
								还差{{ freeExpressPrice.toFixed(2) }}元免运费
								<u-icon name="arrow-right" size="20" color="#999"></u-icon>
							</block>
							<block v-else>总额:¥{{ goodsDataAll.totalMoney || 0 }} 优惠:-¥{{ goodsDataAll.preferential || 0 }}</block>
						</view>
					</view>

					<view class="btn-group">
						<!-- #ifdef MP -->
						<text class="edit-btn" @click="is_edit = !is_edit">{{ is_edit ? '完成' : '编辑' }}</text>
						<!-- #endif -->
						<u-button v-if="!is_edit" :custom-style="btnStyle" shape="circle" @click="createOrder">
							<text v-if="!goodsDataAll.totalMoney">随便逛逛</text>
							<text v-else-if="goodsDataAll.totalMoney < startDeliveryPrice">去凑单</text>
							<text v-else>去结算({{ goodsDataAll.checkNum || 0 }})</text>
						</u-button>
						<u-button v-else type="error" shape="circle" @click="delSelect">删除</u-button>
					</view>
				</view>
			</view>
		</view>
		<!-- 底部tabbar -->
		<Tabbar v-model="tab_current"></Tabbar>
	</view>
</template>
<script>
import Login from '@/components/Login.vue';
export default {
	components: {
		Login
	},
	data() {
		return {
			tab_current: 2,
			is_edit: false,
			totalMoney: 0, //总价格
			buyNum: 1, //更新购物数字
			checkedShop: false, //商铺选择
			allChecked: false, //全选状态  true|false
			empty: false, //空白页现实  true|false
			goodsData: [], //店铺列表
			invalidData: [], //失效商品
			shopGoodsData: [], //商品列表
			options: [
				{
					text: '删除',
					style: {
						backgroundColor: 'rgb(255,58,49)'
					}
				}
			],
			goodsDataAll: {
				activityMoney: '0.00',
				cartNum: 0,
				checkNum: 0,
				expressMoney: 0,
				goodsData: [],
				goodsNum: 0,
				invalidData: [],
				payMoney: '0.00',
				preferential: '0.00',
				totalMoney: '0.00',
				vipDiscount: 0,
				vipDoubleDiscount: 0
			},
			btnStyle: {
				width: '240rpx',
				height: '72rpx',
				lineHeight: '72rpx',
				fontSize: '28rpx'
			}
		};
	},
	// #ifdef APP-PLUS || H5
	onNavigationBarButtonTap(obj) {
		var currentWebview = this.$mp.page.$getAppWebview();
		var tn = currentWebview.getStyle().titleNView;
		// 修改buttons
		// index: 按钮索引, style {WebviewTitleNViewButtonStyles }
		if (!this.is_edit) {
			this.is_edit = true;
			tn.buttons[0].text = '完成'; //[0] 按钮的下标
			currentWebview.setStyle({
				titleNView: tn
			});
		} else if (this.is_edit) {
			// console.log(132312);
			this.is_edit = false;
			tn.buttons[0].text = '编辑'; //[0] 按钮的下标
			currentWebview.setStyle({
				titleNView: tn
			});
		}
	},
	// #endif

	watch: {
		'$store.state.locationObj'(val) {
			if (JSON.stringify(val) === '{}') {
				this.getAuthorizeInfo();
				return;
			}
			if (this.isLogin) {
				this.getCartByUserCenterId();
			}
		},
		isLogin(val) {
			if (val) {
				this.getCartByUserCenterId();
			}
		}
	},
	computed: {
		theme() {
			return this.$store.state.theme;
		},
		theme_color() {
			return this.$store.state.theme_color;
		},
		primaryColor() {
			return this.theme_color ? this.theme_color.primary : '#fa3534';
		},
		// 判断市场常见的几种刘海屏机型 true为刘海机型
		isBang() {
			return this.$_utils.modelmes();
		},
		isLogin() {
			return this.$store.state.hasLogin;
		},
		startDeliveryPrice() {
			return this.$store.state.baseSet.startDeliveryPrice || 0;
		},
		freeExpressPrice() {
			const freeExpressPrice = this.$store.state.baseSet.freeExpressPrice || 0;
			return this.$NP.minus(freeExpressPrice, this.goodsDataAll.totalMoney);
		}
	},
	onLoad() {
		if (JSON.stringify(this.$store.state.locationObj) === '{}') {
			this.getAuthorizeInfo();
		}
		// #ifdef MP-WEIXIN
		// 小程序的原生菜单中显示分享按钮
		uni.showShareMenu({
			withShareTicket: false,
			menus: ['shareAppMessage', 'shareTimeline']
		});
		// #endif
	},

	onShow() {
		if (this.$store.state.hasLogin) {
			this.getCartByUserCenterId();
		}
	},
	onPullDownRefresh() {
		if (this.isLogin) {
			this.getCartByUserCenterId();
		} else {
			uni.stopPullDownRefresh();
		}
	},
	methods: {
		goToLogin() {
			uni.navigateTo({
				url: '/pagesT/binding/bindPhone'
			});
		},
		// 点击添加clacAdd
		clacAdd(e, goods) {
			if (goods.selection === 5) {
				this.goodsDataAll.totalMoney = this.$NP.plus(Number(this.goodsDataAll.totalMoney), Number(goods.price));
			}

			this.updateBuyNum(goods.cartId, e.value);
		},
		// 点击减少数量
		clacSusubtract(e, goods) {
			// if (goods.buyNum === 1) {
			// 	this.$api.msg('商品数量不可以再减少了哦');
			// 	return;
			// }
			if (goods.selection === 5) {
				this.goodsDataAll.totalMoney = this.$NP.minus(Number(this.goodsDataAll.totalMoney), Number(goods.price));
			}

			this.updateBuyNum(goods.cartId, e.value);
		},
		// 手动输入
		numberChange(e, goods) {
			if (e.value <= 0) {
				this.$api.msg('请输入正确的数量');
				return;
			}
			this.updateBuyNum(goods.cartId, e.value);
		},
		// 更新购物车数量 updateBuyNum
		updateBuyNum(id, buyNum) {
			this.$u.api
				.updateBuyNum(id, {
					buyNum: buyNum
				})
				.then(res => {
					this.getCartByUserCenterId();
				})
				.catch(() => {
					this.getCartByUserCenterId();
				});
		},
		//请求数据 获取商品列表
		getCartByUserCenterId() {
			this.$u.api.getCartByUserCenterId().then(({ data }) => {
				uni.stopPullDownRefresh();
				if (Array.isArray(data)) {
					this.goodsDataAll = {
						activityMoney: '0.00',
						cartNum: 0,
						checkNum: 0,
						expressMoney: 0,
						goodsData: [],
						goodsNum: 0,
						invalidData: [],
						payMoney: '0.00',
						preferential: '0.00',
						totalMoney: '0.00',
						vipDiscount: 0,
						vipDoubleDiscount: 0
					};
					this.goodsData = [];
					this.invalidData = [];
					this.$store.commit('commit_cartNum', 0);
					this.$store.commit('commit_cartPrice', 0);
					return;
				}
				this.goodsDataAll = data;
				this.invalidData = data.invalidData || [];
				if (data.goodsData && data.goodsData.length) {
					data.goodsData.forEach(item => {
						item.checkedShop = item.shopGoodsData.every(itemG => itemG.selection === 5);
						item.shopGoodsData.forEach(goods => {
							goods.isShow = false;
						});
					});
					this.goodsData = data.goodsData;
					this.allChecked = this.goodsData.every(item => item.checkedShop);
				} else {
					this.goodsData = [];
				}
				this.$store.commit('commit_cartNum', data.goodsNum);
				this.$store.commit('commit_cartPrice', data.totalMoney);
			});
		},
		//  打开swipeAction
		openItem(i, gi) {
			// 先将正在被操作的swipeAction标记为打开状态，否则由于props的特性限制，
			// 原本为'false'，再次设置为'false'会无效
			let target = this.$u.deepClone(this.goodsData);
			target[i].shopGoodsData[gi].isShow = true;
			this.goodsData = target;
		},
		// 选中切换
		// type 1 单商品；2 店铺切换；3 全选切换
		async checkShop(checked, id, type, row, PRow) {
			const selection = checked ? 4 : 5;
			const params = {
				selection: selection,
				type: type
			};
			if (type === 1) {
				params.cartId = id;
				// 前端手动把选择标示进行切换，优化操作体验
				row.selection = selection;
				PRow.checkedShop = PRow.shopGoodsData.every(itemG => itemG.selection === 5);
				this.allChecked = this.goodsData.every(item => item.checkedShop);
			} else if (type === 2) {
				params.shopId = id;
				// 前端手动把选择标示进行切换，优化操作体验
				row.checkedShop = !checked;
				row.shopGoodsData.forEach(item => {
					item.selection = selection;
				});
				this.allChecked = this.goodsData.every(item => item.checkedShop);
			} else {
				// 前端手动把选择标示进行切换，优化操作体验
				this.allChecked = !checked;
				this.goodsData.forEach(item => {
					item.checkedShop = !checked;
					item.shopGoodsData.forEach(goods => {
						goods.selection = selection;
					});
				});
			}
			this.$u.api
				.updateSelection({
					...params
				})
				.then(res => {
					this.getCartByUserCenterId();
				});
		},
		// 移出商品
		delSelect() {
			let chooseGoods = [];
			this.goodsData.forEach(item => {
				item.shopGoodsData.forEach(itemC => {
					if (itemC.selection === 5) {
						chooseGoods.push(itemC.cartId);
					}
				});
			});
			this.deleteCartItem(chooseGoods);
		},
		// 清空失效
		clearInvalid() {
			let chooseGoods = this.invalidData.map(item => {
				return item.cartId;
			});
			this.deleteCartItem(chooseGoods);
		},
		// deleteCartItem 删除
		deleteCartItem(cartId, row, index, gIndex) {
			if (cartId.length === 0) {
				this.$api.msg('请选择要删除的商品');
				return;
			}
			uni.showModal({
				title: '提示',
				content: '你确定将此产品移除购物车',
				success: res => {
					if (res.confirm) {
						this.$u.api
							.delCart({
								cartId: cartId
							})
							.then(res => {
								this.getCartByUserCenterId();
							});
					}
				}
			});
		},
		//创建订单
		createOrder() {
			// if (this.$store.state.baseSet.personnelReview === 5) {
			// 验证账户状态
			this.userAudit();
			if (!this.isUserAudit) {
				return;
			}
			// }
			if (!this.goodsDataAll.totalMoney) {
				this.goPage('/pages/classification/cate', 'switchTab');
				return;
			}
			if (this.startDeliveryPrice && this.goodsDataAll.totalMoney < this.startDeliveryPrice) {
				// this.$api.msg('请选择要结算的商品');
				this.goPage('/pages/classification/cate', 'switchTab');
				return;
			}
			if (!this.goodsDataAll.checkNum) {
				this.$api.msg('请选择要结算的商品');
				return;
			}
			let isSub = true;
			for (let i in this.goodsData) {
				let item = this.goodsData[i];
				for (let g in item.shopGoodsData) {
					let goods = item.shopGoodsData[g];
					if (goods.selection === 5 && goods.isInvalid === 4) {
						isSub = false;
						break;
					}
				}
			}
			if (!isSub) {
				this.$api.msg('抱歉，您要结算的商品中包含失效商品，请取消后再次进行提交');
				return;
			}
			uni.navigateTo({
				url: `/pagesT/order/createOrder`
			});
		}
	},
	onShareAppMessage(options) {
		return {
			title: this.$store.state.baseSet.shop,
			path: '/pages/index/index?businessmanId=' + (this.$store.state.userStatus.id||''),
			success: res => {
				console.log(res);
			}
		};
	},
	// #ifdef MP-WEIXIN
	// 分享到朋友圈
	onShareTimeline(obj) {},
	// 收藏小程序
	onAddToFavorites() {}
	// #endif
};
</script>

<style lang="scss">
page {
	background-color: #f5f5f5;
}
.cart-page {
	.container {
		padding: 20rpx 20rpx 200rpx;
	}
	.empty-wrapper {
		padding-top: 200rpx;
	}
}

.cart-card {
	background: #ffffff;
	border-radius: 16rpx;
	padding: 0 30rpx;
	margin-bottom: 20rpx;
	.shop-header {
		display: flex;
		align-items: center;
		height: 80rpx;
		border-bottom: 1px solid #f0f0f0;
		.shop-name {
			font-size: 28rpx;
			font-weight: 500;
			margin: 0 16rpx;
			flex: 1;
		}
	}
	.goods-item {
		display: flex;
		align-items: center;
		padding: 24rpx 0;
		border-bottom: 1px solid #f0f0f0;

		&:last-child {
			border-bottom: none;
		}

		.checkbox {
			margin-right: 20rpx;
		}

		.goods-image {
			width: 160rpx;
			height: 160rpx;
			border-radius: 12rpx;
			flex-shrink: 0;
		}

		.goods-info {
			flex: 1;
			margin-left: 20rpx;
			display: flex;
			flex-direction: column;
			justify-content: space-between;
			height: 160rpx;
			.goods-title {
				font-size: 28rpx;
				color: #333;
				display: -webkit-box;
				-webkit-line-clamp: 2;
				-webkit-box-orient: vertical;
				overflow: hidden;
				text-overflow: ellipsis;
				line-height: 1.4;

				&.disabled {
					color: #999;
				}
			}
			.goods-sku {
				font-size: 24rpx;
				color: #999;
			}
			.goods-bottom {
				display: flex;
				justify-content: space-between;
				align-items: flex-end;
				.price-box {
					display: flex;
					align-items: flex-end;
					color: $price-color;
					font-family: DIN-Medium;

					.price-symbol {
						font-size: 24rpx;
						margin-right: 4rpx;
					}
					.price {
						font-size: 36rpx;
						font-weight: 500;
					}
					.unit {
						font-size: 20rpx;
						color: #999;
						margin-left: 4rpx;
					}
					.activity-tag {
						font-size: 20rpx;
						color: #ffffff;
						height: 32rpx;
						line-height: 32rpx;
						text-align: center;
						border-radius: 6rpx;
						margin-left: 10rpx;
						padding: 0 8rpx;
						background-color: $price-color;
					}
				}
			}
		}
	}
}

.invalid-card {
	.invalid-header {
		display: flex;
		align-items: center;
		justify-content: space-between;
		height: 80rpx;
		border-bottom: 1px solid #f0f0f0;

		.invalid-title {
			font-size: 28rpx;
			font-weight: 500;
			color: #333;
		}
		.clear-btn {
			display: flex;
			align-items: center;
			font-size: 24rpx;
			color: #999;
		}
	}
	.invalid-tag {
		background-color: rgba(0, 0, 0, 0.4);
		color: #fff;
		font-size: 22rpx;
		padding: 4rpx 10rpx;
		border-radius: 8rpx;
		position: absolute;
		left: 16rpx;
		top: 16rpx;
	}
	.goods-item {
		position: relative;
	}
	.goods-image {
		opacity: 0.6;
	}
	.invalid-reason {
		font-size: 24rpx;
		color: #fa3534;
		margin-top: 10rpx;
	}
}

/* 底部栏 */
.action-section {
	position: fixed;
	left: 0;
	bottom: 100rpx;
	z-index: 95;
	width: 100%;
	background-color: #ffffff;
	border-top: 1px solid #f0f0f0;

	.action-main {
		display: flex;
		align-items: center;
		justify-content: space-between;
		height: 100rpx;
		padding: 0 30rpx;

		.select-all {
			display: flex;
			align-items: center;
			.text {
				font-size: 28rpx;
				color: #333;
				margin-left: 16rpx;
			}
		}

		.right-area {
			display: flex;
			align-items: center;
		}

		.total-box {
			text-align: right;
			margin-right: 20rpx;
			.price-line {
				margin-bottom: 4rpx;
				.label {
					font-size: 28rpx;
					color: #333;
				}
				.price {
					font-size: 36rpx;
					color: $price-color;
					font-weight: bold;
					font-family: DIN-Medium;
				}
			}
			.sub-line {
				font-size: 22rpx;
				color: #999;
			}
		}
		.btn-group {
			display: flex;
			align-items: center;
			.edit-btn {
				margin-right: 20rpx;
				font-size: 28rpx;
			}
		}
	}
}
</style>
